// 文档状态管理
import { ref } from 'vue'
import { defineStore } from 'pinia'
import {
  getDocumentDetail,
  // getKnowledgeDocuments,
  // getUserDocuments,
  // createDocument,
  // updateDocument,
  // deleteDocument,
  // getRecentDocuments,
  getDocumentVersions,
  createDocumentVersion,
  restoreDocumentVersion,
  deleteDocumentVersion, getRecentDocuments, getSharedDocuments
} from '@/api/document'
import type {
  GetDocumentResponse,
  // CreateDocumentRequest,
  // UpdateDocumentRequest,
  GetRecentDocumentResponse,
  DocumentVersion,
  CreateVersionRequest, GetSharedDocumentResponse, GrantPermissionRequest, GetDocPermissionResponse
} from '@/types/index'
import {getDocPermissionsByUserId, grantPermission} from "@/api/permission.ts";


export const useDocumentStore = defineStore('document', () => {
  // 状态
  const currentDocument = ref<GetDocumentResponse | null>(null)
  const documentVersions = ref<DocumentVersion[]>([])  // 当前文档的版本列表
  const loading = ref(false)
  const error = ref<string | null>(null)
  const recentDocument = ref<GetRecentDocumentResponse[] | null>(null)
  const sharedDocumentList = ref<GetSharedDocumentResponse[] | null>(null)
  const grantDocPermission = ref<Boolean | null>(null)
  const getDocPermission = ref<GetDocPermissionResponse | null>(null)

  // 获取文档详情
  const fetchDocument = async (docId: string, userId: string) => {
    try {
      loading.value = true
      error.value = null
      const result = await getDocumentDetail(docId,userId)
      currentDocument.value = result
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取文档失败'
      console.error('获取文档失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  const fetchCurrentDocument = async (userId: string) => {
    try {
      loading.value = true
      error.value = null
      const result = await getRecentDocuments(userId)
      recentDocument.value = result
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取最近访问文档失败'
      console.error('获取最近访问文档失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  const fetchSharedDocuments = async (userId: string) => {
    try {
      loading.value = true
      error.value = null
      const result = await getSharedDocuments(userId)
      sharedDocumentList.value = result
      console.log(sharedDocumentList.value) // 检查是否能拿到数据
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取共享文档失败'
      console.error('获取共享文档失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  const grantPermissionDocs = async (data: GrantPermissionRequest) => {
    try {
      loading.value = true
      error.value = null
      const result = await grantPermission(data)
      grantDocPermission.value = result
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : '授权失败'
      console.error('授权失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  const fetchDocPermissions = async (docId: string, userId: string) => {
    try {
      loading.value = true
      error.value = null
      const result = await getDocPermissionsByUserId(userId, docId)
      getDocPermission.value = result
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取文档权限失败'
      console.error('获取文档权限失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  // ============= 版本控制相关 =============

  // 获取文档版本列表
  const fetchDocumentVersions = async (docId: string) => {
    try {
      loading.value = true
      error.value = null
      const result = await getDocumentVersions(docId)
      documentVersions.value = result
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取版本列表失败'
      console.error('获取版本列表失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  // 创建文档版本
  const createNewDocumentVersion = async (docId: string, data: CreateVersionRequest, userId: string) => {
    try {
      loading.value = true
      error.value = null
      const result = await createDocumentVersion(docId, data, userId)
      
      // 更新版本列表
      documentVersions.value.unshift(result)
      
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : '创建版本失败'
      console.error('创建版本失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  // 恢复文档版本
  const restoreToVersion = async (docId: string, versionNumber: number, userId: string) => {
    try {
      loading.value = true
      error.value = null
      const result = await restoreDocumentVersion(docId, versionNumber, userId)
      
      // 添加延迟等待后端操作完成
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 恢复成功后重新获取文档内容
      await fetchDocument(docId, userId)
      
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : '恢复版本失败'
      console.error('恢复版本失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  // 删除文档版本
  const removeDocumentVersion = async (docId: string, versionNumber: number) => {
    try {
      loading.value = true
      error.value = null
      const result = await deleteDocumentVersion(docId, versionNumber)
      
      // 从本地状态中移除版本
      documentVersions.value = documentVersions.value.filter(
        v => v.versionNumber !== versionNumber
      )
      
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : '删除版本失败'
      console.error('删除版本失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }
  return {
    // 状态
    currentDocument,
    documentVersions,
    loading,
    error,
    sharedDocumentList,
    
    // 方法
    fetchDocument,
    fetchCurrentDocument,
    fetchSharedDocuments,
    grantPermissionDocs,
    fetchDocPermissions,
    fetchDocumentVersions,
    createNewDocumentVersion,
    restoreToVersion,
    removeDocumentVersion,
  }
}) 